﻿/// <reference path="../../_references.js" />
(function (e) {
    e.views = e.views || {};
    e.views.editcompany = e.view.define({
        templateName: "tmpl_editcompany",
        repo: null,
        load: function (state) {
            var that = this;
            this.repo = new e.repositories.company();
            this.currentId = null;
            var model = { title: loc.newCompany, Name: "", Description: "" };
            if (state.id) {
                that.repo.getCompanyById(parseFloat(state.id), function (err, data) {
                    if (!err && data) {
                        that.currentId = parseFloat(state.id);
                        model = $.extend({}, data, { title: loc.editCompany });
                        that.render(model);
                    }
                });
            } else {
                that.render(model);
            }
        },
        submitCompany: function (form) {
            this.repo.addCompany($(form).serializeObject(), function (err, company) {
                if (!err) {
                    e.changeView("companies");
                    e.flash.success("Company successfully created.");
                }
            });
        },
        updateCompany: function (form, id) {
            var comp = $(form).serializeObject();
            this.repo.updateCompany($.extend(comp, { Id: id }), function (err, company) {
                if (!err) {
                    e.changeView("companies");
                    e.flash.success("Company " + comp.Name + " successfully updated.");
                }
            });
        },
        refresh: function (state) {
            this.load(state);
        },
        afterRender: function () {
            var that = this;
            that.cont.find("input[name=Name]").focus();
            that.cont.find("#editcompanyform").validate(e.validateOptions({
                messages: {
                    Name: {
                        required: loc.validation.companyNameReq
                    }
                },
                submitHandler: function(form) {
                    if (!that.currentId) {
                        that.submitCompany(form);
                    } else {
                        that.updateCompany(form, that.currentId);
                    }
                    return false;
                }
            }));
        },
        unload: function () {
        }
    });
} (this.eg = this.eg || {}));